'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

/**
 * 带单位的字节数据
 * @param {Number} byteSize 字节
 * @param {Number} fixed 小数保留位
 * @returns {String} 0.00MB
 */
const toByteSize = (byteSize = 0, fixed = 2) => {
  return (
    abbrNum({ value: byteSize, base: 1024, fixed, unitCapital: true }) + "B"
  );
};

/**
 * 简化数字
 */
function abbrNum({
  value = 0,
  fixed = 2,
  base = 1000,
  unitCapital = false,
}) {
  const K = base ** 1;
  const M = base ** 2;
  const G = base ** 3;
  const T = base ** 4;

  let size = value;
  let unit = "T";
  if (size >= T) {
    size = size / T;
    unit = "T";
  } else if (size >= G) {
    size = size / G;
    unit = "G";
  } else if (size >= M) {
    size = size / M;
    unit = "M";
  } else if (size > K) {
    size = size / K;
    unit = "K";
  } else {
    unit = "";
  }
  unit = unitCapital ? unit.toUpperCase() : unit.toLowerCase();
  return (size % 1 === 0 ? size : size.toFixed(fixed)) + unit;
}

/**
 * 返回格式为`00:00:00`的时间
 * @param {Number} milliSeconds 毫秒时间
 * @returns {String} 00:00:00
 */
const time = (milliSeconds = 0) => {
  const dayTime = 24 * 60 * 60 * 1000;
  if (milliSeconds > dayTime) {
    return "-- : -- : --";
  }

  const standard = new Date("2000-1-1 00:00:00");
  const relative = new Date(standard.getTime() + milliSeconds);
  const H = relative.getHours();
  const M = relative.getMinutes();
  const S = relative.getSeconds();

  return [H, M, S].map((t) => ("0" + t).slice(-2)).join(":");
};

/**
 * 保留定长，不足补零
 * @param {String | Number} num
 * @param {Number} len 要保留的长度
 * @returns {String}
 */
const cut = (num, len) => {
  return num.toString().padStart(len, "0").slice(-len);
};

const DATE_TIME_FORMAT = "YYYY-MM-DD HH:mm:ss";
const DATE_FORMAT = "YYYY-MM-DD";
const DATE_FORMAT_TM = "YYYY-MM-DD HH:mm";

/**
 * 格式化日期
 * @param {Date} date
 * @param {String} format
 */
const dateFormat = (date = new Date(), format = DATE_TIME_FORMAT) => {
  const Y = date.getFullYear();
  const M = date.getMonth() + 1;
  const D = date.getDate();
  const H = date.getHours();
  const h = H % 12;
  const m = date.getMinutes();
  const s = date.getSeconds();

  return format
    .replace(/Y{4,}/g, cut(Y, 4))
    .replace(/Y{3}/g, cut(Y, 3))
    .replace(/Y{2}/g, cut(Y, 2))
    .replace(/Y/g, cut(Y, 4))
    .replace(/M{2,}/g, cut(M, 2))
    .replace(/M/g, M)
    .replace(/D{2,}/g, cut(D, 2))
    .replace(/D/g, D)
    .replace(/H{2,}/g, cut(H, 2))
    .replace(/H/g, H)
    .replace(/h{2,}/g, cut(h, 2))
    .replace(/h/g, h)
    .replace(/m{2,}/g, cut(m, 2))
    .replace(/m/g, m)
    .replace(/s{2,}/g, cut(s, 2))
    .replace(/s/g, s);
};

exports.DATE_FORMAT = DATE_FORMAT;
exports.DATE_FORMAT_TM = DATE_FORMAT_TM;
exports.DATE_TIME_FORMAT = DATE_TIME_FORMAT;
exports.abbrNum = abbrNum;
exports.dateFormat = dateFormat;
exports.time = time;
exports.toByteSize = toByteSize;
